<template>
	<view class="goods-detail" :class="themeName">
		<navbar title="商品详情" :background="{ background: `rgba(256,256,256,${percent})` }"
			:titleColor="`rgba(0,0,0,${percent})`" :immersive="true"></navbar>
		<!-- 轮播图 -->
		<bubble top="220rpx" :page="2" :discharge="isDischarge"></bubble>
		<goods-swiper :images="goodsInfo.goods_image" :video="goodsInfo.video" :video-cover="goodsInfo.video_cover" />

		<!-- 商品基础信息 -->
		<view class="goods-info">
			<view class="flex row-between col-top">
				<view class="">
					<block v-if="pageCommon.show_goods_price == 1">
						<block v-if="pageCommon.show_price_type == 0">
							<!-- 原价 -->
							<price :content="goodsSpecOptions.spec.sell_price || goodsInfo.sell_price" main-size="46rpx"
								minor-size="32rpx" :color="themeColor" :prefix="goodsInfo.price_symbol">
								<view slot="suffix" class="muted line-through m-l-12 xxs"
									v-show="pageCommon.show_market_price == 1">
									<price :content="goodsSpecOptions.spec.lineation_price || goodsInfo.lineation_price"
										:prefix="$zhTran('原价') + goodsInfo.price_symbol" :line-through="true"
										v-if="Number(goodsInfo.lineation_price)" />
								</view>
							</price>
							<!-- 会员价 用户有登陆且且该商品有设置会员价才显示 -->
							<view class="vip-price flex"
								v-if="(goodsSpecOptions.spec.member_price || goodsInfo.member_price) && !!userInfo.id && pageCommon.show_user_price == 1">
								<view class="price-name xxs">{{ $zhTran('会员价') }}</view>
								<view style="padding: 0 10rpx">
									<price :content="goodsSpecOptions.spec.member_price || goodsInfo.member_price"
										:weight="500" color="#7B3200" :prefix="goodsInfo.price_symbol">
									</price>
								</view>
							</view>
						</block>
						<block v-else>
							<price :content="goodsSpecOptions.spec.member_price || goodsInfo.member_price"
								main-size="46rpx" minor-size="32rpx" :color="themeColor"
								:prefix="goodsInfo.price_symbol">
								<view slot="suffix" class="muted line-through m-l-12 xxs"
									v-show="pageCommon.show_market_price == 1">
									<price :content="goodsSpecOptions.spec.lineation_price || goodsInfo.lineation_price"
										:prefix="$zhTran('原价') + goodsInfo.price_symbol" :line-through="true"
										v-if="Number(goodsInfo.lineation_price)" />
								</view>
							</price>
						</block>
					</block>
				</view>

				<view class="sm lighter share" @tap="showShare = true"
					v-if="!isrebate || rr_goods.activity_rebate_pages">
					<u-icon name="share" />
					<text class="m-l-10">{{ $zhTran('分享') }}</text>
				</view>
			</view>
			<view class="share-money flex m-t-20" v-if="distribution.is_show && distribution.earnings > 0">
				<view class="flex-1">
					{{ $zhTran('好友下单最高可赚') }}
					<text class="bold m-l-14">
						{{ goodsInfo.price_symbol }}{{ distribution.earnings }}
					</text>
				</view>
				<view @tap="showShare = true">
					{{ $zhTran('立即分享') }}
					<u-icon name="arrow-right" />
				</view>
			</view>
			<view class="goods-name lg">{{ goodsInfo.name }}</view>
			<view class="goods-name" v-if="pageCommon.show_goods_tag == 1 && goodsInfo.tag_desc != ''">
				<u-image width="80" height="40" :src="goodsInfo.tag_desc" mode="aspectFit" />
			</view>
			<view class="flex row-between muted xs">
				<template v-if="pageCommon.show_stock == 1">
					<view>{{ $zhTran('库存: ') }}{{ goodsInfo.total_stock }}</view>
				</template>
				<view><text
						v-if="pageCommon.show_goods_salecount == 1">{{ $zhTran('销量: ') }}{{ goodsInfo.sales_num }}</text>
				</view>
				<view>{{ $zhTran('浏览量: ') }}{{ goodsInfo.click_num }}</view>
			</view>
			<view class="flex row-between muted xs word-break-all" v-if="pageCommon.show_goods_code == 1">
				{{ $zhTran('编码：') }}{{ goodsInfo.code == null ? "" : goodsInfo.code }}
			</view>
			<view class="flex row-between muted xs word-break-all" v-if="pageCommon.show_goods_model == 1">
				{{ $zhTran('型号：') }}{{ goodsInfo.goods_model == null ? "" : goodsInfo.goods_model }}
			</view>
			<view class="flex row-between muted xs" v-if="pageCommon.show_goods_desc == 1">
				{{ goodsInfo.goods_desc == null ? "" : goodsInfo.goods_desc }}
			</view>
		</view>
		<!-- 推荐返利 区域 -->
		<view v-if="isrebate">
			<rebatebox @notsati="onBuy" @reload="initGoodsDetail" :rr_goods="rr_goods" :goods_id="goods_id"
				:goodsInfo="goodsInfo"></rebatebox>
		</view>
		<!-- end -->
		<!-- S 优惠 -->
		<view class="nr discounts" v-if="pageCommon.show_goods_coupons == 1">
			<text class="muted">{{ $zhTran('优惠') }}</text>
			<view class="xxs m-l-20 flex-1">
				<view class="flex" @tap="showCoupons = true">
					<u-tag :text="$zhTran('领券')" mode="plain" size="mini" class="m-r-20" :color="themeColor"
						:border-color="themeColor" />
					<block v-for="item in goodsCouponSpecs" :key="item">
						<view class="coupon-tag">{{ item }}</view>
					</block>
					<u-icon name="arrow-right" class="muted nr" style="margin-left: auto" />
				</view>

				<!-- 				<view class="flex m-t-30">
					<u-tag
					  text="积分" 
					  mode="plain" 
					  size="mini" 
					  class="m-r-20"
					  :color="themeColor"
					  :border-color="themeColor" 
					/>
					<text class="nr">{{$zhTran('订单完成可获得 0 积分'}}</text>
				</view> -->
			</view>
		</view>
		<!-- Coupons Popup -->
		<u-popup v-model="showCoupons" mode="bottom" border-radius="14" :closeable="false"
			:safe-area-inset-bottom="true">
			<view class="coupons">
				<view class="coupons-header">
					<text>{{ $zhTran('领券') }}</text>
					<u-icon name="close" color="#666666" @tap="showCoupons = false" />
				</view>

				<view class="coupons-main">
					<!-- 					<view class="flex m-b-30">
										<u-tag
						  text="积分" 
						  mode="plain" 
						  size="mini" 
						  class="m-r-20"
						  :color="themeColor"
						  :border-color="themeColor" 
						/>
						<text class="nr">{{$zhTran('订单完成可获得 0 积分'}}</text>
					</view> -->
					<scroll-view :scroll-y="true" style="height: 700rpx; touch-action: none">
						<view class="coupons-item" v-for="item in goodsCouponList" :key="item.id">
							<coupon-card mode="get" :name="item.name" :money="item.money" :condition="item.condition"
								:time="item.effective_time" :scene="item.use_scene" :coupon-id="item.id"
								:gotten="!!item.is_receive" :prefix="goodsInfo.price_symbol"
								:button="{ name: $zhTran('领取'), theme: 'primary', disable: !!item.is_available }"
								@button="getCoupon" />
						</view>
						<u-empty v-if="!goodsCouponList.length" :text="$zhTran('暂无优惠券')"
							:src="$getImageUri('resource/image/shopapi/uniapp/empty/coupon_icon.png')"
							:icon-size="180" />
					</scroll-view>
				</view>
			</view>
		</u-popup>
		<!-- E 优惠 -->
		<view class="nr specification">
			<text class="muted flex-none">{{ $zhTran('运费') }}</text>
			<text class="m-l-20">{{ goodsInfo.free_shipping_tips || $zhTran('以提交订单时为准') }}</text>
		</view>


		<!-- S 满赠活动 -->
		<view class="nr discounts flex u-flex-wrap" v-if="Object.keys(goodsGiveFullList).length > 0"
			@tap="goGiveFullActivity">
			<view class="flex row-between" style="width: 100%;">
				<text class="muted">{{ $zhTran('满赠活动') }}</text>
				<view class="muted">
					{{ $zhTran('查看更多') }}
					<u-icon name="arrow-right" class="nr" style="margin-left: auto" />
				</view>
			</view>
			<view class="xxs flex-1">
				<view class="m-t-20 flex">
					<u-tag :text="$zhTran('满赠')" mode="plain" size="mini" class="m-r-20" :color="themeColor"
						:border-color="themeColor" />
					<view class="m-l-20" v-if="goodsGiveFullList.condition_type == 1">
						{{ $zhTran('满 ' + goodsGiveFullList.condition_count + ' 件即刻领取赠品（数量有限，赠完即止）') }}
					</view>
					<view class="m-l-20" v-else>
						{{ $zhTran('满 ' + goodsGiveFullList.condition_money + ' 元即刻领取赠品（数量有限，赠完即止）') }}
					</view>
				</view>
			</view>
		</view>
		<!-- E 满赠活动 -->

		<!-- S 规格 -->
		<view class="nr specification" @click="onGoodsOptions">
			<text class="muted flex-none">{{ $zhTran('已选') }}</text>
			<text class="m-l-20">{{ specValueStr }}</text>
			<u-icon name="arrow-right" class="muted" style="margin-left: auto" />
		</view>

		<!-- 规格选择Popup -->
		<goods-spec v-model="showGoodsSpec" v-if="speckey" :defaultInfo="{
			image: goodsInfo.image,
			price: goodsInfo.sell_price,
			stock: goodsInfo.total_stock,
			unit: goodsInfo.unit_name,
			aux_def_id:goodsInfo.aux_def_id,
			show_goods_price: pageCommon.show_goods_price,
			show_stock: pageCommon.show_stock,
			show_goods_buycount: pageCommon.show_goods_buycount,
			show_price_type: pageCommon.show_price_type,
			show_user_price: pageCommon.show_user_price,
		}" :buttons="specButtonsList" :spec-list="goodsInfo.spec_value" :spec-map="goodsInfo.spec_value_list"
			@buy="handleBuy" @cart="handleCartAdd" @change="changeGoodsSpec" :prefix="goodsInfo.price_symbol"
			:understock_order_enabled="goodsInfo.understock_order_enabled" />
		<!-- E 规格 -->

		<!-- diy -->
		<view v-for="(item, index) in pagesData" :key="index">
			<template v-if="item.name == 'goodsbase'">
				<w-goodsbase v-if="item.show" :content="item.content" :styles="item.styles"
					:other_field_data="goodsInfo.other_field_data2" />
			</template>
			<template v-if="item.name == 'reviews'">
				<w-reviews v-if="item.show && pageCommon.show_goods_comment == 1" :content="item.content"
					:styles="item.styles" :comment="goodsComment" :goods-id="goods_id" />
			</template>
			<template v-if="item.name == 'goodsrecom'">
				<w-goodsrecom v-if="item.show" :content="item.content" :styles="item.styles" />
			</template>
		</view>

		<!-- 商品介绍 -->
		<view class="detail" style="margin-top: 30rpx;"
			v-if="goodsInfo.goods_attribute != undefined && goodsInfo.goods_attribute.length > 0">
			<view class="detail-title nr">{{ $zhTran('商品属性') }}</view>
			<u-attr :attr_data="goodsInfo.goods_attribute"></u-attr>
		</view>

		<!-- 商品介绍 -->
		<!-- <view class="detail" style="margin-top: 30rpx;"
			v-if="goodsInfo.other_field_data != undefined && goodsInfo.other_field_data.length > 0">
			<view class="detail-title nr">{{ $zhTran('其他信息') }}</view>
			<u-field-data :field_data="goodsInfo.other_field_data"></u-field-data>
		</view> -->

		<!-- 商品介绍 -->
		<view class="detail">
			<view class="detail-title nr">{{ $zhTran('商品详情') }}</view>
			<u-parse :html="goodsInfo.content" :show-with-animation="true"></u-parse>
		</view>

		<w-jishuzhichi />
		<!-- 功能按钮组 -->
		<view class="functions">
			<view class="icon-group" :style="btnshowNum == 0 ? 'width:100%' : ''">
				<block v-if="pageCommon.show_customer_service == 1">
					<view class="icon-item" @tap="goService" v-if="pageCommon.customer_service_type == 1">
						<u-icon name="kefu-ermai" size="42" />
						<text>{{ $zhTran('客服') }}</text>
					</view>
					<u-button :plain="true" open-type="contact" :custom-style="{
						padding: '0',
					}" type="" :hair-line="false" size="medium" v-else>
						<view style="margin-top: -14rpx;">
							<view style="padding: 0;margin: 0;height: 32rpx;">
								<u-icon name="kefu-ermai" size="42" color="#666666" />
							</view>
							<view style="padding: 0;margin: 0;height: 40rpx;font-size: 22rpx;color: #666666;">
								{{ $zhTran('客服') }}
							</view>
						</view>
					</u-button>
				</block>
				<view class="icon-item" @tap="changeCollect(isGoodsCollect)">
					<template v-if="isGoodsCollect">
						<u-icon name="star-fill" size="42" :color="themeColor" />
					</template>
					<template v-else>
						<u-icon name="star" size="42" />
					</template>
					<text>{{ $zhTran('收藏') }}</text>
				</view>
				<view class="icon-item" @tap="goCart" v-if="pageCommon.show_cart_icon == 1">
					<u-badge :count="cartNum" :offset="[-10, -10]"></u-badge>
					<u-icon name="shopping-cart" size="42" />
					<text>{{ $zhTran('购物车') }}</text>
				</view>
			</view>
			<view class="button-group">
				<view class="button-item button-item--cart" @click="onCart"
					v-if="goodsInfo.type == 1 && pageCommon.show_join_cart_btn == 1">{{ $zhTran('加入购物车') }}</view>
				<view class="button-item button-item--buy" @click="onBuy" v-if="pageCommon.show_buy_btn == 1">
					{{ $zhTran('立即购买') }}
				</view>
			</view>
		</view>

		<share-popup v-model="showShare" :share-id="goods_id" pagePath="bundle2/pages/goods_detail/goods_detail"
			:type="1" />
		<!-- 页面状态 -->
		<page-status :status="pageStatus">
			<template #error>
				<u-empty :text="pageErrorMsg" :src="$getImageUri('resource/image/shopapi/uniapp/empty/shop.png')"
					:icon-size="280"></u-empty>
			</template>
		</page-status>
		<u-back-top :scroll-top="scrollTop" :top="1000" :customStyle="{
			backgroundColor: '#FFF',
			color: '#000',
			boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)',
		}">
		</u-back-top>
	</view>
</template>

<script>
	import {
		apiCartAdd,
		apiCouponGet,
	} from '@/api/store'
	import {
		apiGoodsDetail,
		apiGoodsCollect,
		apiGoodsMarketing,
		apiGoodsStock
	} from '@/api/goods'
	import {
		apiCloudShopStoreInfo,
		apiCloudShopVisit
	} from "@/api/cloudshop"
	import {
		baseURL,
		basePath
	} from '@/config/app'
	import {
		apiGetPage
	} from '@/api/store'
	import {
		PageStatusEnum,
		OrderTypeEnum
	} from '@/utils/enum'
	import {
		mapGetters,
		mapState
	} from 'vuex'
	import {
		strToParams
	} from '@/utils/tools'
	import Cache from '@/utils/cache'
	import rebatebox from "@/bundle2/components/rebatebox.vue";
	export default {
		name: 'GoodsDetail',
		components: {
			rebatebox,
		},
		data() {
			return {
				speckey: 0,
				shareId: '',
				rraId: '',
				isrebate: false, // 商品是否有返利活动
				rr_day: 0, // 剩余天数
				rr_goods: '',

				partishareshow: false,
				isDischarge: false,
				// 页面状态
				pageStatus: PageStatusEnum['LOADING'],
				pagesData: [],
				pageErrorMsg: '', // 页面异常信息
				scrollTop: 0,
				percent: 0,
				showShare: false,
				goodsInfo: {}, // 商品信息
				goodsComment: {}, // 用户评价
				goods_id: '', // 商品ID

				isGoodsCollect: false, // 商品收藏

				showGoodsSpec: false, // 商品规格: 显示 | 隐藏
				showCoupons: false, // 领券：显示 | 隐藏

				goodsSpecOptions: {
					spec: {}
				}, // 已选商品规格
				specButtonsList: [], // 规格按钮
				goodsCouponList: [], // 优惠券列表

				goodsCouponActive: '', // 使用的优惠券
				// 规格按钮组
				specButtonsGroups: {
					buy: {
						event: 'buy',
						text: this.$zhTran('立即购买'),
					},
					cart: {
						event: 'cart',
						text: this.$zhTran('加入购物车'),
					},
				},
				distribution: {},
				pageCommon: {},
				goodsGiveFullList: {}, //满赠活动
				clspInfo: {}
			};
		},

		computed: {
			...mapGetters(["isLogin"]),
			...mapState({
				cartNum: (state) => state.cart.cartNum,
			}),
			// 优惠券【视图】
			goodsCouponSpecs() {
				// 展示数量
				const COUNT = 2;
				const coupons = this.goodsCouponList;
				// 优惠券列表数量
				const Len = coupons.length;
				// 承载容器
				const payload = [];

				for (let i = 0; i < COUNT && i <= Len - 1; ++i) {
					const value = coupons[i]["condition"];
					payload.push(value);
				}

				return payload;
			},

			// 已选商品规格
			specValueStr() {
				return this.goodsSpecOptions?.spec?.spec_value_str ?? "";
			},
			btnshowNum() {
				var num = 0;
				if (this.pageCommon.show_buy_btn == 1) num++;

				if (this.pageCommon.show_join_cart_btn == 1) num++;

				return num;
			},
		},

		methods: {
			getCloudShopInfo() {
				apiCloudShopStoreInfo({
					id: Cache.get('clsp_id')
				}).then(res => {
					this.clspInfo = this.$zhTran(res);
					Cache.set('clspInfo', this.clspInfo)
				})
			},
			// 获取装修页面
			getPage() {
				apiGetPage({
					type: 5,
					goods_id: this.goods_id,
				}).then((data) => {
					const {
						common,
						content
					} = this.$zhTran(data);

					this.pagesData = content;
					this.pageCommon = common;
					if (this.pageCommon.show_stock == undefined) this.pageCommon.show_stock = 0;
					if (this.pageCommon.show_market_price == undefined)
						this.pageCommon.show_market_price = 1;
					if (this.pageCommon.show_goods_code == undefined)
						this.pageCommon.show_goods_code = 0;
					if (this.pageCommon.show_goods_model == undefined)
						this.pageCommon.show_goods_model = 0;
					if (this.pageCommon.show_goods_desc == undefined)
						this.pageCommon.show_goods_desc = 0;
					if (this.pageCommon.show_goods_price == undefined)
						this.pageCommon.show_goods_price = 1;
					if (this.pageCommon.show_goods_tag == undefined)
						this.pageCommon.show_goods_tag = 0;
					if (this.pageCommon.show_buy_btn == undefined) this.pageCommon.show_buy_btn = 1;
					if (this.pageCommon.show_join_cart_btn == undefined)
						this.pageCommon.show_join_cart_btn = 1;
					if (this.pageCommon.show_cart_icon == undefined)
						this.pageCommon.show_cart_icon = 1;
					if (this.pageCommon.show_goods_coupons == undefined)
						this.pageCommon.show_goods_coupons = 1;
					if (this.pageCommon.show_customer_service == undefined)
						this.pageCommon.show_customer_service = 1;
					if (this.pageCommon.customer_service_type == undefined)
						this.pageCommon.customer_service_type = 1;
					uni.setNavigationBarTitle({
						title: common.title,
					});
				});
			},
			// 更改规格
			changeGoodsSpec(options) {
				this.goodsSpecOptions = options;
				console.log('changeGoodsSpec', options);
				if (!this.goodsInfo.understock_order_enabled) {
					//未开启库存不足出库
					apiGoodsStock({
							item_id: options.spec.id,
						})
						.then((data) => {
							let sku_idx = this.goodsInfo.spec_value_list.findIndex(item => item.id == options.spec.id)
							this.$set(this.goodsInfo.spec_value_list[sku_idx], 'stock', data.stock)
							this.$set(this.goodsInfo.spec_value_list[sku_idx], 'stock_desc', data.stock_desc)
						})
						.catch((err) => {
							console.log(err);
						});
				}
			},

			// 点击加入购物车按钮
			onCart() {
				this.showGoodsSpec = true;
				this.specButtonsList = [this.specButtonsGroups.cart];
			},

			// 更改商品收藏状态
			changeCollect(value) {
				value = !!value ? 0 : 1;
				if (!this.isLogin) {
					Cache.set('rraId', this.rraId)
					Cache.set('shareId', this.shareId)
					return this.$Router.push("/bundle2/pages/login/login");
				}

				apiGoodsCollect({
						goods_id: this.goods_id,
						is_collect: value,
					})
					.then((data) => {
						this.isGoodsCollect = value;
					})
					.catch((err) => {
						console.log(err);
					});
			},

			// 去客服
			goService() {
				this.$Router.push({
					path: "/bundle/pages/service/service",
					query: {
						goods_id: this.goods_id,
						type: "normal",
					},
				});
			},

			//去满赠活动详情
			goGiveFullActivity() {
				this.$Router.push({
					path: '/bundle2/pages/give_full_activity/give_full_activity',
				})
			},

			// 去购物车
			goCart() {
				this.$Router.replaceAll({
					path: "/bundle2/pages/shop_cart/shop_cart",
				});
			},
			// 点击立即购买按钮
			onBuy() {
				this.showGoodsSpec = true;
				this.specButtonsList = [this.specButtonsGroups.buy];
			},

			// 领取优惠券
			getCoupon(id) {
				if (!this.isLogin) {
					Cache.set('rraId', this.rraId)
					Cache.set('shareId', this.shareId)
					return this.$Router.push("/bundle2/pages/login/login");
				}

				apiCouponGet({
						id,
					})
					.then(() => {
						this.$toast({
							title: this.$zhTran("领取成功"),
						});
						this.initMarketing();
					})
					.catch((err) => {
						console.log(err);
						// this.$toast({ title: '' })
					});
			},

			// 点击已选规格
			onGoodsOptions() {
				this.showGoodsSpec = true;
				this.specButtonsList = [{
						...this.specButtonsGroups.cart,
						style: {
							border: `solid 1px ${this.themeColor}`,
							color: this.themeColor,
							backgroundColor: "#FFFFFF",
						},
					},
					this.specButtonsGroups.buy,
				];

				if (this.pageCommon.show_join_cart_btn != 1) {
					this.specButtonsList.splice(0, 1);
					if (this.pageCommon.show_buy_btn != 1) this.specButtonsList.splice(0, 1);
				} else {
					if (this.pageCommon.show_buy_btn != 1) this.specButtonsList.splice(1, 1);
				}

				this.showGoodsSpec = true;
			},

			// 处理 加入购物车
			handleCartAdd({
				spec,
				number,
				aux_id
			}) {
				if (!this.isLogin) {
					Cache.set('rraId', this.rraId)
					Cache.set('shareId', this.shareId)
					return this.$Router.push("/bundle2/pages/login/login");
				}

				apiCartAdd({
						item_id: spec.id,
						goods_num: number,
						aux_id,
						clsp_id: Cache.get('clsp_id')
					})
					.then(() => {
						this.$toast({
							title: this.$zhTran("已加入购物车"),
						});
						this.$store.dispatch("getCartNum");
					})
					.catch((err) => {
						throw new Error(err);
					});
			},

			// 处理 立即购买
			handleBuy({
				spec,
				number,
				aux_id
			}) {
				if (!this.isLogin) {
					Cache.set('rraId', this.rraId)
					Cache.set('shareId', this.shareId)
					return this.$Router.push("/bundle2/pages/login/login");
				}

				if (!this.goodsInfo.shop_price_show) {
					uni.showModal({
						content: this.$zhTran('该会员组无权限查看商品价格，无法下单'),
						confirmColor: this.themeColor,
						confirmText: this.$zhTran('确定'),
						showCancel: false
					})
					return false
				}
				if (!this.goodsInfo.order_enabled) {
					uni.showModal({
						content: this.$zhTran('该会员组无权下单'),
						confirmColor: this.themeColor,
						confirmText: this.$zhTran('确定'),
						showCancel: false
					})
					return false
				}

				if (spec.limit_buy > 0) {
					//最小起订量
					let coefficient = 1
					if (aux_id != '') {
						let aux_arr = spec.aux_arr.filter(item => item.id == aux_id)
						coefficient = aux_arr[0].coefficient || 1
					}

					if (spec.limit_buy > number * coefficient) {
						this.$toast({
							title: '最小起订量为' + spec.limit_buy + this.goodsInfo.unit_name
						})
						return false
					}
				}

				const form = this.goodsInfo.type == 1 ? "GOODS" : "VIRTUAL";
				var that = this
				uni.navigateTo({
					url: "/bundle2/pages/goods_order/goods_order",
					events: {
						reCountCarNum(res) {
							that.$store.dispatch("getCartNum");
						}
					},
					success(res) {
						res.eventChannel.emit("receiveData", {
							rra_id: that.rraId,
							rr_share_id: that.shareId,
							from: OrderTypeEnum[form],
							payload: {
								source: "buy_now",
								goods: [{
									goods_num: number,
									item_id: spec.id,
									aux_id,
								}, ],
							},
						});
					}
				});
			},

			// 初始化商品详情数据
			initGoodsDetail() {
				return new Promise((resolve, reject) => {
					apiGoodsDetail({
							id: this.goods_id,
							visit: 1,
							clsp_id: Cache.get('clsp_id'),
							rra_id: this.rraId,
							rr_share_id: this.shareId,
						})
						.then((ndata) => {
							let data = this.$zhTran(ndata)
							this.goodsInfo = data;
							const hasComment = JSON.stringify(data.goods_comment) !== "[]";
							this.goodsComment = hasComment ? data.goods_comment : {};
							this.goodsGiveFullList = data.goods_give_full_list;
							this.isGoodsCollect = !!data.is_collect;
							this.distribution = this.goodsInfo.distribution;

							console.log('goodsInfo', this.goodsInfo)
							// 推荐返利活动
							let robj = data.rr_goods || ''
							console.log('robj', robj)
							this.rr_goods = robj
							this.isrebate = robj ? true : false;
							Cache.set('rra_id', robj.id)

							// 
							return data;
						})
						.then((data) => {
							// #ifdef H5
							// 设置分享
							this.$store.dispatch("setWxShare", {
								shareImage: data?.image,
								shareDesc: this.$zhTran(data?.name),
							});
							// #endif
							this.speckey++
							resolve(data);
						})
						.catch((err) => {
							reject(err);
						});
				});
			},

			// 初始化优惠券
			initMarketing() {
				return new Promise((resolve, reject) => {
					apiGoodsMarketing({
							id: this.goods_id,
						})
						.then((data) => {
							this.goodsCouponList = this.$zhTran(data.coupon);
							resolve(data);
						})
						.catch((err) => {
							reject(err);
						});
				});
			},
		},
		onPageScroll(e) {
			const top = uni.upx2px(100)
			const {
				scrollTop
			} = e;
			this.percent = scrollTop / top > 1 ? 1 : scrollTop / top;
			this.scrollTop = scrollTop;
		},
		async onLoad() {
			const options = this.$Route.query;
			let clsp_id = Cache.get('clsp_id')
			// 商品ID赋值：点击 | 扫码
			console.log('gdetail', options)
			if (options["scene"]) {
				this.goods_id = strToParams(options["scene"])["id"]
				clsp_id = strToParams(options["scene"])["clspId"] || ''
				this.shareId = strToParams(options["scene"])["shareId"] || ''
				this.rraId = strToParams(options["scene"])["rraId"] || ''
			} else {
				this.goods_id = options.id
				clsp_id = options.clspId
				this.shareId = options.shareId
				this.rraId = options.rraId
			}

			if (!Cache.get('clsp_id') && clsp_id) {
				Cache.set('clsp_id', clsp_id)
				Cache.set('cloud_shop_enabled', 1, 24 * 60 * 60)
				apiCloudShopVisit({
					clsp_id: clsp_id
				})
			}

			if (!Cache.get('rraId')) {
				this.rraId = Cache.get('rraId')
				Cache.remove('rraId');
			}

			if (!Cache.get('shareId')) {
				this.shareId = Cache.get('shareId')
				Cache.remove('shareId');
			}

			try {
				if (!this.goods_id) throw new Error(this.$zhTran("该商品不存在"));
				await this.getPage();
				// 商品详情数据
				await this.initGoodsDetail();
				// 促销
				await this.initMarketing();

				if (clsp_id)
					await this.getCloudShopInfo()
				this.pageStatus = PageStatusEnum["NORMAL"];
			} catch (err) {
				console.log(err);
				this.pageErrorMsg = this.$zhTran(err.message);
				this.pageStatus = PageStatusEnum["ERROR"];
			}
		},

		onShareAppMessage() {
			const {
				name,
				image
			} = this.goodsInfo;

			let path = `/bundle2/pages/goods_detail/goods_detail?id=${this.goods_id}&invite_code=${this.userInfo.code}`
			let imageUrl = image
			if (Cache.get('cloud_shop_enabled') && Cache.get('clsp_id')) {
				path += `&clspId=${Cache.get('clsp_id')}`
				imageUrl = this.clspInfo.avatar
			}
			if (this.rr_goods) {
				path += `&shareId=${this.userInfo.id}&rraId=${this.rr_goods.id}`
				imageUrl = this.rr_goods.poster
			}
			return {
				title: this.$zhTran(name),
				path,
				imageUrl,
			};
		},
		onHide() {
			this.isDischarge = true;
		},
		onShow() {
			this.isDischarge = false;
		},
	};
</script>

<style lang="scss" scoped>
	.goods-detail {
		padding-bottom: calc(100rpx + 20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + 20rpx + env(safe-area-inset-bottom));
	}

	.goods-info {
		padding: 20rpx 24rpx;
		background-color: #FFFFFF;

		// 会员价
		.vip-price {
			margin-top: 5rpx;
			background-color: #FFE9BA;
			color: #FFD4B7;
			line-height: 36rpx;
			border-radius: 6rpx;
			overflow: hidden;

			.price-name {
				background-color: #101010;
				padding: 3rpx 12rpx;
				position: relative;
				overflow: hidden;

				&::after {
					content: '';
					display: block;
					width: 20rpx;
					height: 20rpx;
					position: absolute;
					right: -15rpx;
					background-color: #FFE9BA;
					border-radius: 50%;
					top: 50%;
					transform: translateY(-50%);
					box-sizing: border-box;
				}
			}
		}

		.share {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 134rpx;
			height: 60rpx;
			margin-right: -24rpx;
			border-radius: 30px 0 0 30px;
			background-color: #F6f6f6;
		}

		.goods-name {
			padding: 20rpx 0 10rpx 0;
			font-weight: 500;
		}
	}

	.discounts {
		display: flex;
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #FFFFFF;

		.coupon-tag {
			box-sizing: border-box;
			position: relative;
			display: flex;
			justify-content: center;
			min-width: 140rpx;
			height: 36rpx;
			padding: 0 20rpx;
			border-radius: 4px;
			margin-right: 10rpx;
			color: #ffffff;

			@include background_color();

			&::before,
			&::after {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
				display: block;
				content: '';
				width: 10rpx;
				height: 10rpx;
				border-radius: 50%;
				background-color: #FFFFFF;
			}

			&::before {
				right: -5rpx;
			}

			&::after {
				left: -5rpx;
			}
		}
	}

	.specification {
		display: flex;
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #FFFFFF;
	}

	.detail {
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #FFFFFF;

		&-title {
			text-align: center;
			font-weight: 500;
			padding-bottom: 24rpx;
		}

		::v-deep image {
			vertical-align: top;
		}

		// #ifdef H5
		::v-deep img {
			vertical-align: top;
			display: inline;
		}

		// #endif
		// #ifdef MP-WEIXIN || APP-PLUS
		::v-deep ._img {
			vertical-align: top;
			display: inline;
		}

		// #endif
	}

	.functions {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		padding: 0 24rpx constant(safe-area-inset-bottom) 24rpx;
		padding: 0 24rpx env(safe-area-inset-bottom) 24rpx;
		border-top: $-solid-border;
		background-color: #FFFFFF;

		.icon-group {
			display: flex;
			justify-content: space-around;
			width: 268rpx;
			font-size: $-font-size-xxs;
			color: $-color-lighter;

			.icon-item {
				position: relative;
				display: flex;
				flex-direction: column;
				align-items: center;
			}
		}

		.button-group {
			flex: 1;
			display: flex;
			justify-content: space-between;

			.button-item {
				flex: 1;
				box-sizing: border-box;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 74rpx;
				margin-left: 14rpx;
				border-radius: 60px;

				&--cart {
					@include font_color();
					@include border_color();

					border-width: 1px;
					border-style: solid;
				}

				&--buy {
					@include background_color();
					color: #FFFFFF;
				}
			}
		}
	}

	.coupons {
		background-color: #f6f6f6;

		&-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 100rpx;
			padding: 0 30rpx;
			font-weight: 500;
			font-size: $-font-size-md;
			background-color: #FFFFFF;
		}

		&-main {
			padding: 20rpx;

			.coupons-item {
				&:nth-child(n+2) {
					margin-top: 20rpx;
				}
			}
		}
	}

	.share-money {
		border-radius: 8rpx;
		padding: 8rpx 16rpx;
		color: #7b3e0e;
		background: linear-gradient(90deg, #fdeed8 0%, #fccf9c 100%);
	}
</style>